package xyz.chaoslolomonica.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DoubleBarrierExample {
	public static void main(String[] args) throws InterruptedException {
		CuratorFramework client = CuratorFrameworkFactory
				.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
		client.start();

		ExecutorService service = Executors.newFixedThreadPool(5);
		final DoubleDistributedBarrier barrier = new DoubleDistributedBarrier(client, "/example/doublebarrier", 5);

		for (int i = 0; i < 5; ++i) {
			final int index = i;
			Callable<Void> task = new Callable<Void>() {

				@Override
				public Void call() throws Exception {
					Thread.sleep((long) (5 * Math.random()));
					System.out.println("Client #" + index + " waits on distributed barrier");
					String b = barrier.enter();
					System.out.println("Client #" + index + " passed distributed barrier, do work");
					Thread.sleep((long) (3 * Math.random()));
					barrier.leave(b);
					System.out.println("Client #" + index + " leave distributed barrier");
					return null;
				}
			};
			service.submit(task);
		}

		Thread.sleep(20000);
		System.out.println("wait all task done.");

//		barrier.removeEmptyBarrierParent();

		service.shutdown();
		service.awaitTermination(10, TimeUnit.SECONDS);
		client.close();
	}
}
